<template>
  <div class="advanced">
    <div class="advanced-header">
      <div class="advanced-header-title">高级查询</div>
      <!-- <img
        class="advanced-header-close"
        src="../images/header-close.png"
        alt=""
        @click="close"
      /> -->
      <i class="advanced-header-close vul-icon-close" @click="close"></i>
    </div>

    <!-- <div class="advanced-tabs">
      <div
        v-for="info in typeList"
        :key="info.value"
        class="advanced-tabs-tab"
        :class="{ active: info.value == activeType }"
        @click="changeTab(info.value)"
      >
        {{ info.label }}
      </div>
    </div> -->
    <div class="advanced-groups">
      <!-- 组 -->
      <div
        v-for="(group, group_i) in list"
        :key="`group_${group_i}`"
        class="advanced-groups-group"
      >
        <!-- 项 -->
        <div
          v-for="(item, item_i) in group"
          :key="`item_${item_i}`"
          class="advanced-groups-group-item"
        >
          <el-select
            v-model="item.key"
            class="search_select"
            style="width: 126px"
            :popper-append-to-body="false"
            placeholder="选择字段"
            @change="keyChange(item)"
          >
            <el-option
              v-for="opt in advancedSearchOpts[activeType]"
              :key="opt.signValue"
              :label="opt.label"
              :value="opt.signValue"
            ></el-option>
          </el-select>
          <el-select
            v-model="item.matcher"
            class="search_select"
            style="width: 126px"
            :popper-append-to-body="false"
            placeholder="匹配方式"
          >
            <el-option
              v-for="matcher in getInputInfo(item.key).matchingList ||
              matcherOpts"
              :key="matcher.value"
              :label="matcher.label"
              :value="matcher.value"
            ></el-option>
          </el-select>
          <el-date-picker
            v-if="getInputInfo(item.key).inputType === 'date'"
            v-model="item.value"
            class="search_date_picker"
            type="datetime"
            style="width: 310px"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            :append-to-body="false"
            placeholder="请选择日期时间"
          >
          </el-date-picker>
          <el-select
            v-else-if="getInputInfo(item.key).inputType === 'selection'"
            v-model="item.value"
            class="search_select"
            style="width: 310px"
            :popper-append-to-body="false"
            placeholder=""
          >
            <el-option
              v-for="select in getInputInfo(item.key).selection"
              :key="select.value"
              :label="select.label"
              :value="select.value"
            ></el-option>
          </el-select>
          <el-input
            v-else
            v-model.trim="item.value"
            style="width: 310px"
            class="search_input"
            placeholder=""
            :maxlength="1000"
            @input="
              (val) => {
                item.value = val.replace(/(&|\||\(|\))/g, '');
              }
            "
          ></el-input>

          <div
            class="advanced-groups-group-item-del"
            @click="removeItem(group_i, item_i)"
          ></div>
          <div
            v-if="item_i !== group.length - 1"
            class="advanced-groups-group-item-logic"
          >
            <span @click="changeLogic(item)">{{ logicMap[item.logic] }}</span>
          </div>
        </div>
        <div class="advanced-groups-group-add" @click="addItem(group_i)">
          添加条件
        </div>
        <div
          class="advanced-groups-group-del"
          @click="removeGroup(group_i)"
        ></div>
        <div v-if="group_i !== list.length - 1" class="advanced-groups-logic">
          <span @click="changeLogic(group)">{{ logicMap[group.logic] }}</span>
        </div>
      </div>
      <div class="advanced-groups-add" @click="addGroup">
        <i class="el-icon-plus"></i>
        <span>添加条件组</span>
      </div>
      <div class="advanced-groups-submit">
        <span @click="dialogVisible = true">查看语法参考</span>
        <!-- <div class="advanced-groups-submit-btn" @click="toSearch">查询</div> -->
        <el-button type="primary" @click="toSearch">查询</el-button>
      </div>
    </div>

    <el-dialog
      title="查询语法参考"
      v-model="dialogVisible"
      :modal-append-to-body="false"
      width="960px"
    >
      <Reference></Reference>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { typeList, logicMap, matcherOpts } from '../common';
import AdvancedSearch from '../AdvancedSearch';
import { defineProps, defineEmits, ref, computed, onMounted } from 'vue';
import { useStore } from 'vuex';
import { ElMessage } from 'element-plus';
const store = useStore();
const emit = defineEmits(['advancedSearch', 'closeDia']);
const props = defineProps({
  isShow: {
    type: Boolean,
    default: true,
  },
  searchText: {
    type: String,
    default: '',
  },
  category: {
    type: String,
    default: '',
  },
  flag: {
    type: Number,
    default: 1, // 1.web 2.移动应用 3.敏感数据 4.IP 5.域名 6.代码/文件 7.人员组织 8.经营信息 9.供应链 10. 暗网情报 11. 仿冒网站
  },
});
const activeType = ref('sys');
const advancedSearchOpts = ref({});
const advancedSearchOptss=async()=>{
      await store.dispatch('expose/setAdvancedSearchOpts')
       advancedSearchOpts.value = store.state.expose.advancedSearchOpts
    }
const value = ref('');
const list = ref<any>([]);
const dialogVisible = ref(false);
const getInputInfo :any= computed(() => {
  return async (signValue) => {
    await advancedSearchOptss().then(()=>{
      const itemOpt = advancedSearchOpts.value[activeType.value].find(
      (el) => el.signValue === signValue,
    );
    return itemOpt || {};
          });

  };
});

onMounted(() => {
  activeType.value = props.category;
  if (AdvancedSearch.isTemplateStr(props.searchText)) {
    formatData(props.searchText);
  } else {
    resetList();
  }
});
// const changeTab = (type) => {
//   activeType.value = type;
//   resetList();
// }

const keyChange = (item) => {
  item.matcher = '';
  item.value = '';
}
// 将语法树转为便于操作的数组
const formatData = (text) => {
  const lists = AdvancedSearch.parse2Arr(text);
  // 去除非选中模块的筛选项
  // for (let i = 0; i < list.length; i++) {
  //   list[i] = list[i].filter((el) => {
  //     return el.key.startsWith(this.activeType)
  //   })
  // }
  // this.list = list.filter((el) => el.length > 0)
  // if (!this.list.length) {
  //   this.resetList()
  // }
  lists.forEach((e) => {
    e.forEach((item) => {
      if (item.key == 'exposure_risk') {
        item.value = item.value.slice(1, -1);
      }
    });
  });
  list.value = lists;
}
const resetList = () => {
  list.value = [[{ key: '', value: '', matcher: '' }]];
}
// 将数组转为字符转
const arr2Str = () => {  
  const lists = list.value;  
  
  return new Promise((resolve, reject) => {  
    if (!lists.length) {  
      return reject('请添加条件');  
    }  
    let templateStr = '';  
    for (let i = 0; i < lists.length; i++) {  
      const group = lists[i]; // 使用 lists 而不是 list  
      let groupStr = '';  
      let hasError = false; // 用来跟踪是否有错误  
  
      for (let i2 = 0; i2 < group.length; i2++) {  
        const item = group[i2];  
        if (!item.key) {  
          hasError = true;  
          break; // 跳出内层循环  
        }  
        if (!item.value) {  
          hasError = true;  
          break;  
        }  
        if (!item.matcher) {  
          hasError = true;  
          break;  
        }  
  
        // 添加引号，但只在首次访问时  
        if (!item.value.startsWith('"') && !item.value.endsWith('"')) {  
          item.value = `"${item.value}"`;  
        }  
  
        groupStr += `${item.key}${item.matcher}${item.value}${  
          i2 < group.length - 1 ? item.logic || '' : '' 
        }`;  
      }  
  
      if (hasError) {  
        return reject('请补全字段'); 
      }  
  
      groupStr = `(${groupStr})`;  
      templateStr += `${groupStr}${i < lists.length - 1 ? list[i].logic || '' : ''}`; // 只在非最后一个组时添加 logic  
    }  
  
    resolve(templateStr);  
  });  
};
// 搜索
const toSearch = async () => {
  try {
    const str = await arr2Str();
    emit('advancedSearch', str, activeType.value);
    close();
  } catch (err:any) {
    ElMessage.warning(err);
    // message.$el.style.zIndex += 20000
  }
}
// 添加条件项
const addItem = (groupIndex) => {
  list.value[groupIndex].push({ key: '', value: '', matcher: '' });
  const pre = list.value[groupIndex][list.value[groupIndex].length - 2];
  if (pre) {
    pre.logic = '&&';
  }
}
// 清除条件项
const removeItem = (groupIndex, itemIndex) => {
  if (list.value[groupIndex].length === 1) {
    const message = ElMessage.warning('请删除条件组');
    // message.$el.style.zIndex += 20000
    return;
  }
  list.value[groupIndex].splice(itemIndex, 1);
}
// 添加条件组
const addGroup = () => {
  list.value.push([{ key: '', value: '', matcher: '' }]);
  const pre = list.value[list.value.length - 2];
  if (pre) {
    pre.logic = '&&';
  }
}
// 清除条件组
const removeGroup = (groupIndex) => {
  list.value.splice(groupIndex, 1);
}
// 修改逻辑关系
const changeLogic = (item) => {
  item.logic = item.logic === '&&' ? '||' : '&&';
  // this.$forceUpdate()
}
// 关闭弹窗
const close = () => {
  ElMessage.closeAll();
  emit('closeDia', false);
}
</script>
<style lang="scss" scoped>
.advanced {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  overflow-y: scroll;
  background: $-white;
  font-family: PingFangSC-Regular;
  z-index: 2000;
  &-header {
    padding: 0 16px;
    height: 54px;
    background: $-white;
    display: flex;
    align-items: center;
    justify-content: space-between;
    &-title {
      font-family: PingFangSC-Semibold;
      font-size: 16px;
    }
    &-close {
      width: 20px;
      height: 20px;
      cursor: pointer;
    }
  }

  &-tabs {
    justify-content: center;
    display: flex;

    &-tab {
      display: flex;
      justify-content: center;
      align-items: center;
      box-sizing: border-box;
      padding: 0 10px;
      min-width: 90px;
      height: 40px;
      font-size: 14px;
      // color: #8590b3;
      // border-top: 1px solid #8590b3;
      // border-bottom: 1px solid #8590b3;
      cursor: pointer;
      &.active {
        background: $-white;
        border: 1px solid $-v-color-primary;
        color: $-v-color-primary;
      }
    }

    &-tab:first-of-type {
      border-left: 1px solid #8590b3;
      &.active {
        border-left: 1px solid $-v-color-primary;
      }
    }

    &-tab:last-of-type {
      border-right: 1px solid #8590b3;
      &.active {
        border-right: 1px solid $-v-color-primary;
      }
    }
  }

  &-groups {
    position: relative;
    width: 662px;
    margin: 24px auto 0;
    &-group {
      margin-bottom: 10px;
      padding-top: 10px;
      position: relative;
      min-height: 90px;
      border-radius: 4px;
      border: 1px solid rgb(220, 223, 230);
      &-item {
        margin: 0 0 10px 42px;
        display: flex;
        position: relative;
        &-del {
          display: inline-block;
          width: 40px;
          height: 40px;
          background: $-white url(../images/item-close.png) no-repeat center;
          border: 1px solid rgb(220, 223, 230);
          box-sizing: border-box;
          cursor: pointer;
        }
        &-logic {
          position: absolute;
          top: 20px;
          left: -20px;
          width: 20px;
          height: calc(100% + 12px);
          box-sizing: border-box;
          border: 1px solid rgb(220, 223, 230);
          border-right: none;
          border-radius: 4px 0 0 4px;
          span {
            position: absolute;
            top: 50%;
            left: -21px;
            width: 42px;
            height: 42px;
            font-size: 20px;
            line-height: 42px;
            text-align: center;
            background: #ccc;
            border-radius: 50%;
            transform: translateY(-50%) scale(0.5);
            cursor: pointer;
          }
        }
      }

      &-add {
        margin: 0 auto 10px;
        text-align: center;
        width: 80px;
        font-size: 14px;
        color: $-v-color-primary;
        cursor: pointer;
      }

      &-del {
        width: 20px;
        height: 20px;
        position: absolute;
        top: 50%;
        right: -10px;
        transform: translateY(-50%);
        border-radius: 50%;
        background: url(../images/group-close.jpg);
        background-size: 100% 100%;
        cursor: pointer;
      }
    }

    &-logic {
      position: absolute;
      top: 80px;
      left: -20px;
      width: 20px;
      height: calc(100% + 12px);
      box-sizing: border-box;
      border: 1px solid #5c637b;
      border-right: none;
      border-radius: 4px 0 0 4px;
      span {
        position: absolute;
        top: 50%;
        left: -21px;
        width: 42px;
        height: 42px;
        font-size: 20px;
        line-height: 42px;
        text-align: center;
        background: #ccc;
        border-radius: 50%;
        transform: translateY(-50%) scale(0.5);
        cursor: pointer;
      }
    }

    &-add {
      width: 100%;
      height: 40px;
      font-size: 14px;
      line-height: 40px;
      text-align: center;
      color: $-v-color-primary;
      border: 1px solid $-v-color-primary;
      border-radius: 4px;
      cursor: pointer;
      i {
        font-size: 15px;
        font-weight: 600;
        margin-right: 10px;
      }
    }

    &-submit {
      margin: 30px 0;
      display: flex;
      justify-content: center;
      align-items: center;
      span {
        margin-right: 40px;
        font-size: 14px;
        color: $-v-color-primary;
        cursor: pointer;
      }
      &-btn {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 120px;
        height: 40px;
        font-size: 12px;
        border-radius: 4px;
        color: $-white;
        cursor: pointer;
      }
    }
  }
}
</style>

<style lang="scss">
@mixin placeholder-color($color: rgba(133, 144, 179, 0.6)) {
  &::placeholder {
    color: $color;
  }
  &::-webkit-input-placeholder {
    color: $color;
  }
  &:-moz-placeholder {
    color: $color;
  }
  &::-moz-placeholder {
    color: $color;
  }
  &:-ms-input-placeholder {
    color: $color;
  }
}

.search_select {
  //下拉框
  .el-select-dropdown {
    border: none;
  }
  //输入框
  .el-input__inner {
    border-radius: 0;
    height: 38px;
    line-height: 38px;
    @include placeholder-color;
  }

  .popper__arrow {
    display: none;
  }
}

.search_input {
  .el-input__inner {
    border-radius: 0;

    height: 38px;
    line-height: 38px;
    @include placeholder-color;
  }
}
.el-date-table__row {
  color: $-v-color-white;
}
.el-date-table td.current:not(.disabled) span {
  background-color: rgb(92, 99, 123);
}
.search_date_picker {
  .el-input__inner {
    border-radius: 0;
    border: 1px solid #5c637b;
    @include placeholder-color;
  }
  .el-picker-panel {
    border: 1px solid #5c637b;
  }

  .el-date-picker__time-header {
    border-bottom: 1px solid #5c637b;
  }
}
</style>
